﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using System.Xml;

namespace Infrastructure.Crosscutting.NetFramework.Result
{
    public class CustomXmlReuslt : ActionResult
    {
        public string FileName { get; set; }

        public string Content { get; set; }

        public string Charset { get; set; }

        public System.Text.Encoding Encode { get; set; }

        public CustomXmlReuslt(string content, string name, string charset, System.Text.Encoding encode)
        {
            this.Content = content;
            this.FileName = name;
            this.Charset = charset;
            this.Encode = encode;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(Content);
            XmlDeclaration decl = document.FirstChild as XmlDeclaration;
            if (decl != null)
            {
                decl.Encoding = "utf-8";
            }
            context.HttpContext.Response.Charset = this.Charset;
            context.HttpContext.Response.ContentType = "text/xml";
            context.HttpContext.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xml", FileName));
            context.HttpContext.Response.BinaryWrite(this.Encode.GetBytes(document.InnerXml));
            context.HttpContext.Response.End();
        }
    }
}
